import { Injector } from '@angular/core';
import { DomService, RefreshFormService, WebCmdService } from '@farris/designer-services';
import { ControlService } from '../../../../service/control.service';
import { DgControl } from '../../../../utils/dg-control';
import { IdService } from '@farris/ui-common';

export class ListFilterBuilderService {

    private domService: DomService;
    public refreshFormService: RefreshFormService;
    private controlService: ControlService;
    private webCmdService: WebCmdService;

    constructor(private injector: Injector) {

        this.domService = this.injector.get(DomService);
        this.refreshFormService = this.injector.get(RefreshFormService);
        this.controlService = this.injector.get(ControlService);
        this.webCmdService = this.injector.get(WebCmdService);
    }
    /**
     * 在列表上方创建筛选条
     */
    createListFilterInDocument(fieldConfigs: any[], datGridViewModelId: string, dataGridId: string) {


        // 1、组装筛选条容器和筛选条dom结构
        const listFilterContainer = this.controlService.getControlMetaData(DgControl.ContentContainer.type);
        const listFilterMetadata = this.controlService.getControlMetaData(DgControl.ListFilter.type);

        const gridPrefix = Math.random().toString(36).substr(2, 4);
        Object.assign(listFilterContainer, {
            id: 'list-filter-container-' + gridPrefix,
            appearance: {
                class: 'f-filter-container'
            },
            contents: [listFilterMetadata]
        });

        Object.assign(listFilterMetadata, {
            id: 'list-filter-' + gridPrefix,
            filterList: fieldConfigs || []
        });

        // 2、在列表上方插入筛选条容器
        const gridComponent = this.domService.getComponentByVMId(datGridViewModelId);
        const dataGridContainer = this.domService.getControlParentById(gridComponent, dataGridId);
        if (!dataGridContainer) {
            return;
        }
        const index = dataGridContainer.contents.findIndex(c => c.id === dataGridId);
        if (index === 0) {
            dataGridContainer.contents.unshift(listFilterContainer);
        } else {
            dataGridContainer.contents.splice(index, 0, listFilterContainer);
        }

        // 3、预制筛选条查询命令
        const viewModel = this.domService.getViewModelById(datGridViewModelId);
        let newFilterCommandId;
        if (viewModel && viewModel.commands) {
            let commandCode;
            const filterCommand = viewModel.commands.find(command => command.handlerName === 'Filter' && command.cmpId === '70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72')
            if (filterCommand) {
                commandCode = filterCommand.code;
            } else {
                newFilterCommandId = new IdService().generate();
                commandCode = `${viewModel.id.replace(/-/g, '')}Filter1`;
                // const loadCommand = viewModel.commands.find(command => command.handlerName === 'Filter' && command.cmpId === '70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72')
                const commandParam = this.getFilterCommandParam(datGridViewModelId, gridComponent.id);

                viewModel.commands.push(
                    {
                        id: newFilterCommandId,
                        code: commandCode,
                        name: '过滤列表数据1',
                        params: [
                            {
                                name: 'commandName',
                                shownName: '过滤回调方法',
                                value: commandParam && commandParam.commandName
                            },
                            {
                                name: 'frameId',
                                shownName: '目标组件',
                                value: commandParam && commandParam.frameId
                            }
                        ],
                        handlerName: 'Filter',
                        cmpId: '70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72',
                        shortcut: {},
                        extensions: []
                    }
                );
            }
            listFilterContainer.contents[0].query = commandCode;
        }

        // 4、预置筛选条查询数据的构件
        if (this.domService.module.webcmds) {
            let loadDataCmd = this.domService.module.webcmds.find(cmd => cmd.id === '70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72');
            if (!loadDataCmd) {
                loadDataCmd = {
                    id: '70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72',
                    path: 'Gsp/Web/webcmp/bo-webcmp/metadata/webcmd',
                    name: 'ListController.webcmd',
                    refedHandlers: []
                };
                this.domService.module.webcmds.push(loadDataCmd);
            }
            if (newFilterCommandId) {
                loadDataCmd.refedHandlers.push(
                    {
                        host: newFilterCommandId,
                        handler: 'Filter'
                    }
                );

            }
        }

        // 因为涉及到新增【ListController控制器】，所以这里需要获取控制器信息，方便交互面板展示命令数据
        this.webCmdService.checkCommands();
    }

    /**
     * 移除列表上方的筛选条
     * @param viewModelId 列表所属视图模型ID
     * @param dataGridId 列表控件id
     */
    removeListFilterInDocument(viewModelId: string) {
        const gridComponent = this.domService.getComponentByVMId(viewModelId);
        const node = this.domService.selectNodeAndParentNode(gridComponent, item => item.type === DgControl.DataGrid.type, null);
        const gridParentNode = node.parentNode;

        const listFilterContainerIndex = gridParentNode.contents.findIndex(c => c.type === DgControl.ContentContainer.type &&
            c.appearance && c.appearance.class && c.appearance.class.includes('f-filter-container'));
        if (listFilterContainerIndex < 0) {
            // console.log('未检测到筛选条容器');
            return;
        }
        const listFilterContainer = gridParentNode.contents[listFilterContainerIndex];
        if (!listFilterContainer.contents || listFilterContainer.contents.findIndex(c => c.type === DgControl.ListFilter.type) < 0) {
            // console.log('未检测到筛选条控件');
            return;
        }

        gridParentNode.contents.splice(listFilterContainerIndex, 1);

    }

    private getFilterCommandParam(datGridViewModelId: string, dataGridComponentId: string) {
        const templateId = this.domService.module.templateId;
        const rootViewModel = this.domService.module.viewmodels[0];
        const dataGridViewModel = this.domService.getViewModelById(datGridViewModelId);

        switch (templateId) {
            // 列表模板、带导航的列表模板：从根组件中找ListController.webcmd或者EditableListController.webcmd控制器的load命令
            case 'list-component': case 'list-template': case 'nav-list-template': {
                const loadCommand = rootViewModel.commands.find(command => command.handlerName === 'Load' && ['70b4abd4-9f2c-4b7c-90e9-6ac6f4b74c72', 'd7ce1ba6-49c7-4a27-805f-f78f42e72725'].includes(command.cmpId));
                if (loadCommand) {
                    return { commandName: loadCommand.code, frameId: '#{root-component}' };
                }
                break;
            }
            // 列表带侧边栏模板：从根组件中找AdvancedListCardWithSidebarController.webcmd控制器的LoadList命令
            case 'list-with-sidebar-template': {
                const loadCommand = rootViewModel.commands.find(command => command.handlerName === 'LoadList' && command.cmpId === 'c121742e-6028-48bf-817c-1dda7fb098df');
                if (loadCommand) {
                    return { commandName: loadCommand.code, frameId: '#{root-component}' };
                }
                break;
            }
            //  多数据源列卡模板：从根组件中找AdvancedListCardController.webcmd控制器的LoadList命令
            case 'list-dic-template': {
                const loadCommand = dataGridViewModel.commands.find(command => command.handlerName === 'LoadList' && '45be24f9-c1f7-44f7-b447-fe2ada458a61' === command.cmpId);
                if (loadCommand) {
                    return { commandName: loadCommand.code, frameId: `${dataGridComponentId}` };
                }
                break;
            }
            // 列卡模板：从根组件中找ListCardController.webcmd控制器的loadList命令
            case 'list-card-template': {
                const loadCommand = dataGridViewModel.commands.find(command => command.handlerName === 'loadList' && '7c48ef46-339c-42d4-8365-a21236c63044' === command.cmpId);
                if (loadCommand) {
                    return { commandName: loadCommand.code, frameId: `${dataGridComponentId}` };
                }
                break;
            }
            // 双列表模板、带侧边栏的双列表、标签式双列表：从根组件中找ListListController.webcmd控制器的LoadNavList命令
            case 'double-list-template': case 'double-list-with-sidebar-template': case 'double-list-in-tab-template': {
                const loadCommand = dataGridViewModel.commands.find(command => command.handlerName === 'LoadNavList' && '26436aa8-88a7-4aee-bf0b-9843c1e8afbf' === command.cmpId);
                if (loadCommand) {
                    return { commandName: loadCommand.code, frameId: `${dataGridComponentId}` };
                }
                break;
            }
        }
    }
}
